<!-- 群发软文 -->
<template>
  <div  class="dashboard-editor-container">
    <el-tabs type="border-card" @tab-click="handleTabClick">
      <el-tab-pane label="邮件软文">
        <el-row style="background: #fff; padding: 16px; margin-bottom: 32px">
            <div class="btn">
              <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加邮件内容</el-button>
              <el-button type="warning" icon='el-icon-thumb' @click="emailTesting()" :disabled="contentOfEmail.length === 0">邮件效果测试</el-button>
            </div>
            <el-table stripe border :data="contentOfEmail" style="width: 100%; margin-top: 15px">
              <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
              <el-table-column label="邮件名称" prop="Descp" ></el-table-column>
              <el-table-column label="邮件标题" show-overflow-tooltip prop="Title"  width="400px"></el-table-column>
              <el-table-column label="邮件正文尺寸" show-overflow-tooltip prop="size" width="120px" ></el-table-column>
              <!-- <el-table-column label="编辑员工" show-overflow-tooltip prop="size" width="120px" ></el-table-column> -->
              <!-- <el-table-column label="审核状态"  width="100px">
                <template slot-scope="scope">
                  <p style="color:#909399" v-if="scope.row.Status === 0" type="info">等待审核</p>
                  <p style="color:#67C23A" v-if="scope.row.Status === 1" type="success">审核成功</p>
                  <p style="color:#F56C6C" v-if="scope.row.Status === 2" type="danger">审核拒绝</p>
                </template>
              </el-table-column> -->
              <el-table-column label="操作"  width="180px">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" @click="changeMailCount(scope.row)">修改</el-button>
                  <el-button size="mini" type="danger" @click="deleteMailcontent(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="网络图片">
        <groupResources />
      </el-tab-pane>
      <el-tab-pane label="人工智能">
        <artificialIntelligence />  
      </el-tab-pane>
    </el-tabs>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape=false title="网络图片" :visible.sync="imgdialog" v-el-drag-dialog width="500px">
      <el-select v-model="webImgurl" style="width:100%;margin-bottom: 10px;">
        <el-option v-for="(item, index) in webImgList" :key="index" :value="item.URL" :label="item.Descp">22</el-option>
      </el-select>
      <img :src="webImgurl" style="width:100%" :alt="webImgurl">
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="choseImg()">确 定</el-button>
        <el-button type="info" @click="imgdialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape=false title="分隔符" :visible.sync="delimiterDialog" v-el-drag-dialog width="500px">
      <el-select v-model="Delimiter" style="width:100%;margin-bottom: 10px;">
        <el-option value="[%datetime%]" label="日期时间"></el-option>
        <el-option value="[%date%]" label="日期"></el-option>
        <el-option value="[%time%]" label="时间"></el-option>
        <el-option value="url" label="公司网址"></el-option>
        <el-option value="[%line%]" label="随机分隔行"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="choseDelimiter()">确 定</el-button>
        <el-button type="info" @click="delimiterDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-press-escape=false
      top="5vh"
      :title="Action === 1 ? '添加邮件通知任务' : '修改邮件通知任务' "
      :visible.sync="maildialog"
      v-el-drag-dialog
      :close-on-click-modal = false
      width="60%">
      <el-form label-width="120px" :model="contentForm" :rules="rules" ref="resourceForm">
        <el-form-item label='邮件名称:' prop="Descp">
          <el-input type="texteart" v-model="contentForm.Descp"></el-input>
        </el-form-item>
        <el-form-item label='邮件标题:' prop="Title">
          <el-input v-model="contentForm.Title"></el-input>
        </el-form-item>
        <el-form-item label='邮件内容:' prop="ContentHtml">
          <el-tabs type="border-card" class="tabs">
            <el-tab-pane label="编辑邮件">
              <editor-bar
                :value="editorhtml"
                :link="contentForm.link"
                v-model="ContentHtml"
                @change="editorchange"
                @fileclick="fileclick"
                @imgdialogopen="imgdialogopen"
                @delimiter="delimiter"
                @aiSoftText="aiSoftText"
                :rows="2"
                ref="editor"
              ></editor-bar>
              <input style="display:none" type="file" ref="filetemplete" @change="filetempleteChange($event)" accept=".html,.txt">
            </el-tab-pane>
            <!-- <el-tab-pane label="自定义邮件">
              <el-button @click="$refs.filetemplete.click()">邮件上传</el-button>
            </el-tab-pane> -->
            <el-tab-pane label="查看源码">
              <el-input
                type="textarea"
                :rows="18"
                @blur="changesourceCode()"
                placeholder="请输入内容"
                v-model="sethtml">
              </el-input>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item label='附件:'>
          <el-upload
            class="upload-demo"
            action="#"
            multiple
            ref="upload"
            :on-change="filechange"
            :http-request="uploadFile"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="5"
            :on-exceed="handleExceed"
            :file-list="fileList">
            <el-button size="small" type="primary" >点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendContent()">确 定</el-button>
        <el-button type="info" @click="maildialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { connrequest, uploadfile } from '@/api/firstPage'
import { getuuid, bytesToSize, parseTime } from '@/utils/index'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import EditorBar from '@/components/EditorBar'
import groupResources from './groupResources'
import artificialIntelligence from './artificialIntelligence'
import { getToken } from '@/utils/auth' // get token from cookie
export default {
directives: { elDragDialog },
components: { EditorBar, groupResources, artificialIntelligence },
data() {
  return {
    textAreaNum: [''],
    errMail:[],
    pageNum: 1,
    pageSize: 10,
    total: 10,
    mailboxList:[],
    contentOfEmail:[],
    webImgList:[],
    emailForm: {},
    emailList: [],
    fileList: [],
    emaliList:[],
    webImgurl: '',
    imgurl:'',
    Delimiter: '',
    webImglink:'',
    dialogVisible: false,
    emaildialog: false,
    maildialog: false,
    imgdialog: false,
    delimiterDialog: false,
    resourceForm: {
      file:'',
      remark:'',
      resourceContent:`
      `
    },
    contentForm: {},
    editorhtml: '',
    ContentHtml: '',
    sethtml:'',
    Action: 1,
    rowNum: 1,
    rules: {
      Name:[
        { required: true, message: "请选择接收对象"}
      ],
      CreateTime:[
        { required: true, message: "请选择创建时间"}
      ],
      Title:[
        { required: true, message: "请输入邮件标题"}
      ],
      Descp: [
        { required: true, message: "请输入邮件名称"}
      ]
    }
  }
},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
    this.getwebImg()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  // watch: {
  //   textAreaNum: {
  //     handler(newValue, oldValue) {
  //       this.textAreaNum = newValue.toString()
  //       this.rowNum = this.textAreaNum.split(',').filter(d=>d).length
  //     },
  //     deep: true
  //   }
  // },
  methods: {
    handleTabClick(tab){
      if (tab.label === '邮件软文') {
        this.getData()
        this.getwebImg()
      }
    },
    async getwebImg(){
      const res = await connrequest('GetEMailResList')
      res.Data = res.Data || []
      res.Data.map(item => {
        item.CreateTime = parseTime(item.CreateTime)
        return item
      })
      this.webImgList = res.Data
    },
    async emailTesting(){
      let loading = null
      const res = await connrequest('GetParamMailGlobal')
      if(!res.Data.FromAccount || !res.Data.ToAccount || !res.Data.Pwd || !res.Data.SmtpServer){
        this.$message.info('请在邮件通知的参数配置中配置好企业内部邮箱')
        return
      }
      loading = this.$loading({
          lock: true,
          text: '邮箱测试中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        try{
          const data =  await connrequest('TestMailGlobalAD')
          if(data.Status.StatusCode === 0){
            loading.close();
            this.$message.success('邮箱测试成功')
          }
        }catch {
          loading.close();
        }
    },
    
    aiSoftText(){
      this.$message.info('该功能开发中')
    },
    sysHandleScroll() {
      this.$nextTick(() => {
        const textarea = document.getElementById('text');
        textarea.scrollTop = this.$refs.textAreaNumBox.scrollTop
      })
    },
    
    handleInputText(val){
      this.textAreaNum = this.resourceForm.resourceContent.split("\n")
    },
    imgdialogopen(){
      this.webImgurl = ''
      this.webImglink = ''
      this.imgdialog = true
    },
    editorchange(val){
      this.editorhtml = val
      this.sethtml = val
    },
    delimiter(){
      this.Delimiter = ''
      this.delimiterDialog = true
    },
    choseImg(){
      if(this.webImgurl === ''){
        this.$message.error('请选择图片')
        return false
      }
      this.$refs.editor.insertImg(this.webImgurl);
      this.imgdialog = false
    },
    async choseDelimiter(){
      if(this.Delimiter === ''){
        this.$message.error('请选择分隔符')
        return false
      }
      this.$nextTick(async ()=>{
        if(this.Delimiter == 'url'){
          const res = await connrequest('GetDCDInfo')
          this.$refs.editor.setTxT(`<a style="color:blue;border-bottom:1px solid blue" href="[%corp_url%]">${res.Data.CorpName}</a>`)
          this.delimiterDialog = false
        }else{
          this.editorhtml = this.editorhtml += this.Delimiter
          this.$refs.editor.setTxT(this.Delimiter)
          this.delimiterDialog = false
        }
      })
    },
    querySearch(queryString, cb) {
      var restaurants = this.emailList;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    filetempleteChange(e){
      let file = e.target.files[0]
      if(file.name.indexOf("html") < 0 && file.name.indexOf("txt") < 0){
        this.$message.error('请选择html格式或txt格式的文件')
        this.$refs.filetemplete.value = ''
        return false
      }
      // FileReader对象，h5提供的异步api，可以读取文件中的数据。
      const reader = new FileReader()
      // readAsText是个异步操作，只有等到onload时才能显示数据。
      reader.readAsText(file)
      reader.onload = () => {
        //当读取完成后回调这个函数,然后此时文件的内容存储到了result中
        this.sethtml = reader.result
        this.$refs.editor.sethtml(this.sethtml)
        this.$refs.filetemplete.value = ''
      }
    },
    async TestMailGlobal(row){
      const data = {
        Data: {
          WebSite: row.WebSite,
          CorpName: row.CorpName
        }
      }
      const res = await connrequest('SetEMailTaskADBasic', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('保存成功')
      }
    },
    deleteMailGlobal(row){
      this.Action = 3
      this.resourceForm = {...row}
      this.$confirm('此操作将删除该邮箱, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: this.Action,
            Detail: {
              ...this.resourceForm
            }
          }
        }
        const res = await connrequest('EditEMailTaskADToAccounts', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.dialogVisible = false
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async getData() {
      const res = await connrequest('GetEMailADSubject')
      this.emailForm = res.Data
      
      if(res.Data){
        res.Data.forEach(item => {
          item.Title = Buffer.from(item.Title, 'base64').toString('utf8')
          item.size = bytesToSize(item.ContentHtml.length)
        })
      }
      // res.Data.ToAccount.map(item => {
      //   let arr = Buffer.from(item.Accounts, 'base64').toString('utf8').split('\n')
      //   item.AccountCount = arr.filter(Boolean).length || 0
      //   return item
      // })
      // this.mailboxList = res.Data.ToAccount || []
      this.contentOfEmail = res.Data || []
    },
    checkMailGlobal(row){
      this.emaildialog = true
      let Accounts = Buffer.from(row.Accounts, 'base64').toString('utf8')
      this.emaliList = Accounts
    },
    filechange(file, fileList){
      let arr = []
      fileList.map(item => {
        arr.push({FileName: item.name, InnerName: item.uid + ''})
      })
      this.Attach = arr
    },
    // 添加邮件内容
    addResources(){
      this.Action = 1
      this.maildialog = true
      this.$nextTick(()=>{
        this.contentForm = {}
        this.$refs.editor.clearText()
        this.$refs['resourceForm'].resetFields()
      })
    },
    // 添加群发内容
    async sendContent(){
      this.$refs['resourceForm'].validate(async (valid) => {
        if(valid){
          const row = this.contentOfEmail.findIndex(item => item.Descp === this.contentForm.Descp)
          if(row !== -1 && this.Action === 1){
            this.$message.error('该邮件名称已经存在')
            return false
          }
          if(this.ContentHtml === ''){
            this.$message.error('请输入邮件内容')
            return false
          }
          if(this.Action === 1){
            let html = `
            <!doctype html>
            <html lang="en">
            <head>
              <meta charset="UTF-8">
              <meta http-equiv="X-UA-Compatible" content="IE=edge">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <title>Document</title>
            </head>
            <body>
              ${this.ContentHtml}
            </body>
            <style>
              *{
                margin: 0
                padding: 0
              }
              img{
                vertical-align:left;
                display:block;
              }
            </style>
            </html>`
            const data = {
              Data:{
                Action: 1,
                Detail:{
                  Status: 0,
                  SubjectID: getuuid(),
                  Title: Buffer.from(this.contentForm.Title, 'utf-8').toString('base64'),
                  Descp: this.contentForm.Descp,
                  Attach:this.Attach,
                  ContentHtml: Buffer.from(html, 'utf-8').toString('base64')
                }
              }
            }
            const res = await connrequest('EditEMailADSubject', data)
            if(res.Status.StatusCode === 0){
              this.$message.success('添加邮件内容成功')
              this.maildialog = false
              this.getData()
            }
          }else{
            this.changeMailCountSubmit()
          }
        }
      })
    },
    // 修改
    async changeMailCount(row){
      this.Action = 2
      this.ContentHtml = Buffer.from(row.ContentHtml, 'base64').toString('utf8')
      this.contentForm = {...row}
      if(row.Attach?.length > 0){
          row.Attach.map(item => {
          item.name = item.FileName
          return item
        })
      }
      this.Attach = row.Attach
      this.fileList = row.Attach
      this.maildialog = true
      this.$nextTick(()=>{
        this.editorhtml = row.Subject
        this.$refs.editor.updateText()
        // this.$refs.upload.clearFiles()
      })
    },
    // 修改提交
    async changeMailCountSubmit(){
      const data = {
        Data:{
          Action: 2,
          Detail:{
            Status: 0,
            SubjectID: this.contentForm.SubjectID,
            Title: Buffer.from(this.contentForm.Title, 'utf-8').toString('base64'),
            Descp: this.contentForm.Descp,
            Attach:this.Attach,
            ContentHtml: Buffer.from(this.ContentHtml, 'utf-8').toString('base64')
          }
        }
      }
      const res = await connrequest('EditEMailADSubject', data)
      if(res.Status.StatusCode === 0){
        this.$message.success(this.Action === 1 ? '添加邮件内容成功' : '修改邮件内容成功')
        this.maildialog = false
        this.getData()
      }
    },
    async deleteMailcontent(row){
      this.$confirm('此操作将删除该任务, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: 3,
            Detail: {
              ...row
            }
          }
        }
        const res = await connrequest('EditEMailADSubject', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    fileclick(){
      this.$refs.filetemplete.click()
    },
    async uploadFile(file){
      let formData = new FormData();
      formData.append('CmdCode', "UploadEMailAttatch");
      formData.append('FileName', file.file.name);
      formData.append('InnerName', file.file.uid);
      formData.append('file', file.file);
      formData.append('Token', getToken());
      const res = await uploadfile('UploadEMailAttatch',formData)
      if(res.Status.StatusCode === 0) {
        this.$message.success('文件上传成功')
      }
    },
    handlePreview(){},
    async handleRemove(file, fileList) {
      const data = {
        Data:{
          InnerName: file.uid
        }
      }
      const res = await connrequest('DeleteEMailAttach', data)
      if(res.Status.StatusCode === 0){
        this.Attach = this.Attach.filter(item => item.uid !== file.uid);
        this.Attach = this.Attach.filter(item => item.InnerName != file.uid);
        this.$message.success('文件删除成功')
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    }
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "~@/styles/variables.scss";
.content {
  margin-top: 0;
  width: 800px;
  position: relative;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .title{
    margin-bottom: 10px;
  }
  ::v-deep .certification{
    .el-form-item{
      margin-bottom: 10px;
    }
    .el-col{
      display: flex;
      justify-content: space-between;
      align-items: center;
      p{
        width: 100px;
        display:block;
        color: #aaa;
        font-size: 12px;
        padding-left: 20px;
        white-space: nowrap;
      }
    }
  }
}
.top{
  flex-wrap: nowrap;
}
.key-word-textarea {
  height: 170px;
  overflow: hidden;
  box-shadow: 0px -1px 5px 0px rgba(220, 229, 255, 0.7);
  border: 1px solid #D3D5E0;
  border-top: none;
  align-items: flex-start;
  .el-textarea ::v-deep {
    .el-textarea__inner {
      border: none;
      border-radius: 0;
      line-height: 20px;
      font-size: 14px;
      height: 172px !important;
      min-height: 172px !important;
    }
  }
}


.text-area-num-scroll {
  width: 80px;
  overflow: hidden;
  height: 180px;
  background: #F5F6FA;
  padding-top: 5px;
}
.text-area-num-box {
  min-height: 172px;
  overflow-y: auto;
  height: 172px;
  width: 70px;
  padding-bottom: 10px;
}
.text-area-num {
  line-height: 20px;
  width: 50px;
  text-align: center;
}
.flex {
  display: flex;
}

</style>